package com.ljj.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljj.commonutils.JwtUtils;
import com.ljj.commonutils.R;
import com.ljj.orderservice.entity.Order;
import com.ljj.orderservice.service.OrderService;
import com.ljj.servicebase.handler.MicroCloudException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author ljj
 * @since 2020-09-17
 */
@RestController
@RequestMapping("/orderservice/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 生成订单
     * 远程调用获取课程信息和用户信息
     */
    @PostMapping("{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId  = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)){
            throw new MicroCloudException(30000,"操作需要登录");
        }
        String orderNo = orderService.createOrder(courseId,memberId);
        return R.ok().data("orderNo",orderNo);
    }

    /**
     * 查询订单信息
     */
    @GetMapping("{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo){
        QueryWrapper<Order> wrapper = new QueryWrapper();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("order",order);
    }

    @GetMapping("isbuy/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count > 0){
            return true;
        }else{
            return false;
        }
    }

}

